<script setup lang="ts">
import { ref } from 'vue'
import OneStepForm from './components/fill_step_one.vue'
import TwoStepForm from './components/fill_step_two.vue'
import type { FillOneForm, FillTwoForm, FullForm } from '@/types/member'
import { useMemberStore } from '@/stores'
import { createInfoCard, getUserCard, updateInfoCard } from '@/services/userCard'
import { onShow } from '@dcloudio/uni-app'

const query = defineProps<{
  type: string
}>()

const step = ref('one')
const fullForm = ref<FullForm>({
  name: '',
  sex: '',
  pid: '',
  tel: '',
  birthday: '',
  medicalHistory: [],
  insuranceType: '',
})
const stepHandle = (value: { data: FillOneForm | FillTwoForm; step: number }) => {
  const memberStore = useMemberStore()
  if (value.step === 1) {
    Object.assign(fullForm.value, value.data)
    memberStore.setFullForm(fullForm.value)
    step.value = 'two'
  } else if (value.step === 2) {
    Object.assign(fullForm.value, value.data)
    memberStore.setFullForm(fullForm.value)
    submitHandle()
  }
}

const showLoading = ref(false)
const submitHandle = () => {
  uni.showModal({
    title: '提示',
    content: query.type === 'insert' ? '确定创建就诊卡？' : '确定更新就诊卡信息？',
    success: async (res) => {
      if (res.confirm) {
        const memberStore = useMemberStore()
        showLoading.value = true
        if (query.type === 'insert') {
          await createInfoCard({
            ...fullForm.value,
            type: query.type,
          })
        } else {
          await updateInfoCard({
            ...fullForm.value,
            userId: memberStore.profile!.id,
          })
        }
        showLoading.value = false
        memberStore.clearFullForm()
        uni.switchTab({
          url: '/pages/mine/mine',
        })
      }
    },
  })
}

const successHandle = (res: any) => {
  console.log(res)
}

onShow(async () => {
  const memberStore = useMemberStore()
  if (memberStore.profile?.id) {
    await getUserCard().then((res) => {
      memberStore.setFullForm(res.result)
    })
  }
})
</script>

<template>
  <view>
    <view class="top-container">
      <view class="step-container">
        <view class="icon-1"><text class="desc">个人基本信息</text></view>
        <view class="line"></view>
        <view class="icon-2"><text class="desc">疾病史与社保</text></view>
        <view class="line"></view>
        <view class="icon-3"><text class="desc">创建就诊卡</text></view>
      </view>
    </view>
    <OneStepForm @nextStep="stepHandle" v-show="step === 'one'" />
    <u-transition :show="step === 'two'" mode="fade-right">
      <TwoStepForm @nextStep="stepHandle" v-show="step === 'two'" />
    </u-transition>
    <u-loading-page :loading="showLoading" loadingText="正在提交..."></u-loading-page>
  </view>
</template>

<style lang="less">
@import url(fill_user_info.less);
</style>
